using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;

using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ACM.cmsarea08.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
    public class DatePicker : TextBox
    {
		

    	public string minDate {
    		get {
    			object o=ViewState["minDate"];
    			if(o!=null) return o.ToString();
    			return string.Empty;
    		}
    		set {
    			ViewState["minDate"] = value;
    		}
    		
    	}

		public DatePicker()
		{
            

			
		}
		
        protected override void OnLoad(EventArgs e)
        {
        	//this.ReadOnly = true;
            base.OnLoad(e);
            string currentLang =System.Globalization.CultureInfo.CurrentUICulture.Name; 
            if(currentLang.Length<5) {
            	//for(System.Globalization.CultureInfo.GetCultures()
            	currentLang = "it-IT";
				System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(currentLang);
 			    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(currentLang);            	
            }
            
            
            string embedobjecturl = "/template/plugins/calendar_eightsix/calendar-eightysix-v1.0.1.js";//Page.ClientScript.GetWebResourceUrl(typeof(EmbedInput), "ACM.cmsarea08.Controls.Resources.EmbedObject.js");
            //string clientobjecturl = "/template/plugins/vlaCalendar/vlaCal-v2.1-clientside-v1.0.1-compressed.js";//Page.ClientScript.GetWebResourceUrl(typeof(EmbedInput), "ACM.cmsarea08.Controls.Resources.EmbedObject.js");
            
            string cssembedobjecturl = "/template/plugins/calendar_eightsix/css/calendar-eightysix-default.css";//Page.ClientScript.GetWebResourceUrl(typeof(EmbedInput), "ACM.cmsarea08.Controls.Resources.EmbedObject.css");
           // HttpContext.Current.Response.Write("--> " + embedobjecturl);

            if(this.Page is ACM.cmsarea08.Core.MainPage) {
//            	((ACM.cmsarea08.Core.MainPage)this.Page).RegisterMooTools();
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript("/template/plugins/mootools-1.2-core.js");
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript("/template/plugins/mootools-1.2-more.js");
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript(embedobjecturl);
                //((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript(clientobjecturl);
                
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomCss(cssembedobjecturl);
            } else {
            	//includi lo script... mootools..
            	if(this.Page.Header!=null) {
            		System.Web.UI.HtmlControls.HtmlHead myhead = this.Page.Header;
					bool foundMo = false;
                    bool foundMoMore = false;
					bool foundEb = false;
                    bool foundEbc = false;
                    bool foundCb = false;
					for(int i = 0; i <myhead.Controls.Count;i++) {
						if(myhead.Controls[i] is LiteralControl) {
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("mootools-1.2-core.js") != -1)
                            {
								foundMo=true;
							}
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("mootools-1.2-more.js") != -1)
                            {
                                foundMoMore = true;
                            }

							if(((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("calendar-eightysix-v1.0.1.js")!=-1) {
								foundEb=true;
							}
//							if(((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("vlaCal-v2.1-clientside-v1.0.1-compressed.js")!=-1) {
//								foundCb=true;
//							}
                            
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("calendar-eightysix-default.css") != -1)
                            {
                                foundEbc = true;
                            }

						}
					}
					if(!foundMo) {
                        LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\"/template/plugins/mootools-1.2-core.js\"></script>");
						myhead.Controls.Add(ct);			
					}
                    if (!foundMoMore)
                    {
                        LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\"/template/plugins/mootools-1.2-more.js\"></script>");
                        myhead.Controls.Add(ct);
                    }            		

					if(!foundEb) {
						LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\""+embedobjecturl+"\"></script>");
						myhead.Controls.Add(ct);			
					}
//					if(!foundCb) {
//						LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\""+clientobjecturl+"\"></script>");
//						myhead.Controls.Add(ct);			
//					}
                    
                    if (!foundEbc)
                    {
                        LiteralControl ct = new LiteralControl("<style type=\"text/css\" media=\"screen\">\n"+
                            "<!--\n"+
                            "@import url(\""+cssembedobjecturl+"\");\n"+
                            "-->\n</style>");
                        myhead.Controls.Add(ct);
                    }             		
            		
            	}
            }
        }		
        protected override void Render(HtmlTextWriter writer)
        {
        	string currentLang =System.Globalization.CultureInfo.CurrentUICulture.Name;
        	
			//this.ID
			//this.ClientID
			//this.UniqueID
			writer.Write("<div id=\""+this.ClientID+"_container\" class=\"datePicker\" >");
			base.Render(writer);
		    writer.Write("</div>\n");
		    
		    
		    string dateSep = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.DateSeparator;
		    string dateForm = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
		    string shortDay = "";string.Join("','",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.DayNames);
		    string monthName = "";string.Join("','",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames);
		    //string shortmonthName = "";string.Join("','",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames);
		    
		    
		    for(int i  = 0 ; i<System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.DayNames.Length;i++) {
		    	string giorno = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.DayNames[i];
		    	shortDay+="'" + giorno + "'"; //(giorno.Length>3?giorno.Substring(0,3):giorno)
		    	if(i<System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.DayNames.Length-1)
		    		shortDay+=",";
		    }
		    for(int i  = 0 ; i<System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames.Length;i++) {
		    	string mese = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i];
		    	//shortmonthName+="'" + (mese.Length>3?mese.Substring(0,3):mese) + "'";
		    	monthName+="'" + mese + "'";
		    	if(i<System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames.Length-1) {
		    		monthName+=",";
		    		//shortmonthName+=",";
		    	}
		    }		    
		    string[] dT = dateForm.ToLower().Split(Convert.ToChar(dateSep));
		    string dateOrder = "";
		    
		    string _minDate = "";
		    if(minDate!=string.Empty) {
		    	_minDate = "'minDate':'";
		    	switch (minDate.ToLower()) {
		    		case "today":
		    			_minDate+=DateTime.Now.ToShortDateString() + "'";break;
		    		case "tomorrow":
		    			_minDate+=DateTime.Now.AddDays(1).ToShortDateString() + "'";break;
		    		case "yesterday":
		    			_minDate+=DateTime.Now.AddDays(-1).ToShortDateString() + "'";break;
		    		default:
			    		DateTime dt_ = DateTime.Now;
			    		DateTime.TryParse(minDate,out dt_);
			    		_minDate+=DateTime.Now.ToShortDateString() + "'";
			    		break;
		    	}
		    }
		    dateForm = "";
		    // %m/%d/%Y
		    
		    for(int i = 0;i<dT.Length; i++) {
		    	if(dT[i].StartsWith("d")) {
		    		dateForm+="%d" + dateSep;
		    		dateOrder="'date',";
		    	}
		    	if(dT[i].StartsWith("m")) {
		    		dateForm+="%m" + dateSep;
		    		dateOrder+="'month',";
		    	}
		    	if(dT[i].StartsWith("y")){
		    		dateForm+="%y" + dateSep;
		    		dateOrder="'year',";
		    	}
		    }
		    if(dateForm.EndsWith(dateSep)) dateForm = dateForm.Substring(0,dateForm.Length-dateSep.Length);
		    if(dateOrder.EndsWith(",")) dateOrder = dateOrder.Substring(0,dateOrder.Length-1);
			
		    //'minDate': '1/1/2010'
		    
		    writer.Write("<script language=\"javascript\" type=\"text/javascript\" defer=\"defer\">\n");
		    writer.Write("window.addEvent('domready', function() {\n");
		    writer.Write("MooTools.lang.set('"+currentLang+"', 'Date', { " + 
				"months:    ["+monthName+"], " + 
				"days:      ["+shortDay+"], " + 
				"dateOrder: ["+dateOrder+", '"+dateSep+"'] " +
				"});");
		    writer.Write("MooTools.lang.setLanguage('"+currentLang+"'); ");
            writer.Write("var " + this.ID + "dtPick = new CalendarEightysix('"+this.ClientID+"' , {" +
		                 " format: '"+dateForm+"'" +
		                 "" + (_minDate.Length>0?(","+_minDate + ""):"") +
		                 " });\n");
		    writer.Write("});");
		    
            writer.Write("</script>\n");
		    
		    
		    
		    
		    

        }
        
	}
}
